package ciel.utils;

import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;

import org.mt4j.AbstractMTApplication;

import ciel.debugging.CielDebugger;
import ciel.image.CielImage;
import ciel.res.CielSettings;

public class CielHtmlCreator {
	
	private static HashMap<String, CielImage> images;
	private static ArrayList<CielImage> img;
	private static String folderName;
	
	public static void exportHTML(HashMap<String, CielImage> images) {
		images = images;
		img = new ArrayList<CielImage>();
		
		for(String filename: images.keySet()) {
			img.add(images.get(filename));
		}
		
		makeDirs();
		makeOverviewPage();
		openNewFile();
	}
	
	private static void openNewFile() {
//		  if( !java.awt.Desktop.isDesktopSupported() ) {
//
//	            System.err.println( "Desktop is not supported (fatal)" );
//	            System.exit( 1 );
//	        }
//
//	        if ( args.length == 0 ) {
//
//	            System.out.println( "Usage: OpenURI [URI [URI ... ]]" );
//	            System.exit( 0 );
//	        }
//
//	        java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
//
//	        if( !desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) {
//
//	            System.err.println( "Desktop doesn't support the browse action (fatal)" );
//	            System.exit( 1 );
//	        }
//
//	        for ( String arg : args ) {
//
//	            try {
//
//	                java.net.URI uri = new java.net.URI( arg );
//	                desktop.browse( uri );
//	            }
//	            catch ( Exception e ) {
//
//	                System.err.println( e.getMessage() );
//	            }
//	        }
	}

	private static void makeDirs() {
		folderName = "ciel";
		
		String pathToFolder = CielSettings.Filesystem.HTMLDIR + AbstractMTApplication.separatorChar + folderName;
		File f = new File(pathToFolder);
		f.mkdirs();
		
		pathToFolder = CielSettings.Filesystem.HTMLDIR + AbstractMTApplication.separatorChar + folderName + AbstractMTApplication.separatorChar + "thumbs";
		f = new File(pathToFolder);
		f.mkdirs();
		
		pathToFolder = CielSettings.Filesystem.HTMLDIR + AbstractMTApplication.separatorChar + folderName + AbstractMTApplication.separatorChar + "img";
		f = new File(pathToFolder);
		f.mkdirs();
		
		
		for(CielImage image: img) {
			File orginalImage = new File(CielSettings.Filesystem.IMAGEDIR + AbstractMTApplication.separatorChar + (String) image.getUserData("name"));
			File orginalThumb = new File(CielSettings.Filesystem.THUMBDIR + AbstractMTApplication.separatorChar + (String) image.getUserData("name"));;
			File htmlImage = new File(CielSettings.Filesystem.HTMLDIR + AbstractMTApplication.separatorChar + folderName + AbstractMTApplication.separatorChar + "img" + AbstractMTApplication.separatorChar + (String) image.getUserData("name"));
			File htmlThumb = new File(CielSettings.Filesystem.HTMLDIR + AbstractMTApplication.separatorChar + folderName + AbstractMTApplication.separatorChar + "thumbs" + AbstractMTApplication.separatorChar + (String) image.getUserData("name"));
		
			CielDebugger.log("Copying files:\n" + orginalImage.getAbsolutePath() + " to " + htmlImage.getAbsolutePath());
			CielDebugger.log("Copying files:\n" + orginalThumb.getAbsolutePath() + " to " + htmlThumb.getAbsolutePath());
			
			try {
				copyFile(orginalImage, htmlImage);
				copyFile(orginalThumb, htmlThumb);
			} catch (Exception e) {
			}
 		
		}
	}
	
	private static void makeOverviewPage() {
		String html = CielSettings.HtmlSnippets.HTML_HEADEROVERVIEW;
		ArrayList<String> links = new ArrayList<String>();
		
		
		for(CielImage i: img) {
			String name = (String) i.getUserData("name");
			makeSinglePageForImage(i);
			links.add("<a href='img/"+(String)i.getUserData("name")+".html' ><img src='img/"+name+"' width='100' height='100' /></a>");
		}
		
		html += "<h1>Ciel Image Export</h1>";
		html += "<table>";
		
		int count = 0;
		
		for(String s: links) {
			if(count == 0) {
				html += "<tr>";
			}
			
			html += "<td>" + s + "</td>";
			
			if(count == 5) {
				html += "</tr>";
				count = -1;
			}
			count++;
		}
		
		html += "<table>";
		html += CielSettings.HtmlSnippets.HTML_FOOTER;
		writeHtmlFile("index", CielSettings.Filesystem.HTMLDIR + AbstractMTApplication.separatorChar + folderName, html);
	}

	private static void makeSinglePageForImage(CielImage image) {
		
		String name = (String) image.getUserData("name");
		String note = (String) image.getNote();
		String backlink = "<a href='../index.html'>zur&uuml;ck</a>";
		String img = "<a href='"+name+"' target='_blank'><img src='"+name+"' height='400px' border='2' /></a>";
		
		String html = CielSettings.HtmlSnippets.HTML_HEADER;
		html += "<p>"+backlink+"<br />"+"<h1>"+name+"</h1>"+"<br />"+img+"<br />"+note+"</p>";
		html += CielSettings.HtmlSnippets.HTML_FOOTER;
		
		writeHtmlFile(name, CielSettings.Filesystem.HTMLDIR + AbstractMTApplication.separatorChar + folderName + AbstractMTApplication.separatorChar + "img", html);
		
	}
	
	private static void writeHtmlFile(String name, String path, String content) {
		CielDebugger.log("Writing File: "+name);
		File file = new File(path + AbstractMTApplication.separatorChar + name + ".html");
		FileWriter writer;
	     try { 
	    	 	writer = new FileWriter(file ,false);
	    	 	writer.write(content);
	    	 	writer.flush();
	    	 	writer.close();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	}
	
	public static void copyFile(File in, File out) 
	        throws IOException 
	    {
	        FileChannel inChannel = new
	            FileInputStream(in).getChannel();
	        FileChannel outChannel = new
	            FileOutputStream(out).getChannel();
	        try {
	            inChannel.transferTo(0, inChannel.size(),
	                    outChannel);
	        } 
	        catch (IOException e) {
	            throw e;
	        }
	        finally {
	            if (inChannel != null) inChannel.close();
	            if (outChannel != null) outChannel.close();
	        }
	    }
}
